package com.heer.gymnasium.service;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.SystemClock;
import android.support.annotation.Nullable;
import android.util.Log;

import com.heer.gymnasium.api.ResponseData.ApiResponse;
import com.heer.gymnasium.api.SignHelper;
import com.heer.gymnasium.AppHelper;
import com.heer.gymnasium.broadreceiver.AlarmMessageRecever;
import com.heer.gymnasium.event.BaseEvent;
import com.heer.gymnasium.event.EventConstant;
import com.heer.gymnasium.module.message.beans.NewMsgNumBean;

import org.greenrobot.eventbus.EventBus;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

/**
 * Created by admin on 2017/8/2.
 */

public class MessageService extends Service {


    public AppHelper mAppHelper;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        Log.e("Messagesercive","Messagesercive__________________________________");
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        mAppHelper = AppHelper.context();
        SignHelper sign = new SignHelper("");
        mAppHelper.apiService().getMsgNewNum(sign.GetParameter("token")).enqueue(new Callback<ApiResponse<NewMsgNumBean>>() {
            @Override
            public void onResponse(Call<ApiResponse<NewMsgNumBean>> call, Response<ApiResponse<NewMsgNumBean>> response) {
                if (response.isSuccessful())
                {
                    if (response.code()==200)
                    {
                        if (Integer.valueOf(response.body().getData().getNewMsgnum())>0)
                        {
                            BaseEvent event = new BaseEvent(EventConstant.USER_NEW_MSG,"");
                            EventBus.getDefault().post(event);
                        }
                    }
                    AlarmManager manager=(AlarmManager)getSystemService(ALARM_SERVICE);
                    long triggertime= SystemClock.elapsedRealtime()+30*1000;
                    Intent i=new Intent(getApplicationContext(), AlarmMessageRecever.class);
                    PendingIntent pi=PendingIntent.getBroadcast(getApplicationContext(),0,i,0);
                    manager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggertime,pi);
                }
            }

            @Override
            public void onFailure(Call<ApiResponse<NewMsgNumBean>> call, Throwable t) {

            }
        });



        return super.onStartCommand(intent, flags, startId);
    }
}
